package br.com.foxline.atlasmobile;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.enums.Comando;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;
import br.com.foxline.atlasmobile.util.SharedPreference;

public class CreateMainActivity extends Activity {

	String[] fatores = new String[] { "FATOR 12", "FATOR 18", "FATOR 24" };

	private static String IMOVEL = "getimovel";

	// DAO
	private ImovelDao imovelDao;
	private Spinner comandoSpinner;
	private Spinner fatorLocal;

	private EditText inscd;
	private EditText inscs;
	private EditText inscQuadra;
	private EditText inscLote;
	private EditText inscUnid;

	private Imovel imovel;

	private AlertDialog dialog;
	
	private void setKeyChange() {
		inscd.addTextChangedListener(keyChangeFocus(2, inscs));

		inscs.addTextChangedListener(keyChangeFocus(2, inscQuadra));

		inscQuadra.addTextChangedListener(keyChangeFocus(3, inscLote));

		inscLote.addTextChangedListener(keyChangeFocus(4, inscUnid));

	}
	
	private TextWatcher keyChangeFocus(final int qtd, final EditText nextEdit) {
		return new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence value, int arg1, int arg2,
					int arg3) {

				if (value != null && value.length() == qtd) {
					nextEdit.requestFocus();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		};
	}

	private void load() {
		inscd = (EditText) findViewById(R.id.insc_d);
		inscs = (EditText) findViewById(R.id.insc_s);
		inscQuadra = (EditText) findViewById(R.id.insc_quadra);
		inscLote = (EditText) findViewById(R.id.lote);
		inscUnid = (EditText) findViewById(R.id.insc_unid);
		comandoSpinner = (Spinner) findViewById(R.id.comando_spinner);
		fatorLocal = (Spinner) findViewById(R.id.fatorlocal_spinner);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_main);

		load();

		ArrayAdapter<String> fatorArray = new ArrayAdapter<String>(
				getApplicationContext(), R.layout.spinner_item, fatores);

		ArrayAdapter<Comando> comandoArray = new ArrayAdapter<Comando>(
				getApplicationContext(), R.layout.spinner_item,
				Comando.values());

		fatorLocal.setAdapter(fatorArray);
		comandoSpinner.setAdapter(comandoArray);

		imovel = new Imovel();

		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovelDao = new ImovelDao(getApplicationContext());
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);

			if (imovelSincronizado()) {
				avisoCadastroSincronizado();
			}

			load();

			comandoSpinner.setSelection(Arrays.asList(Comando.values())
					.indexOf(imovel.getComando()));
			fatorLocal.setSelection(Arrays.asList(fatores).indexOf(
					imovel.getFatorLocalizacao()));

			inscd.setText(convert(imovel.getInscricaoCadastralD()));
			inscs.setText(convert(imovel.getInscricaoCadastralS()));
			inscQuadra.setText(convert(imovel.getInscricaoCadastralQuadra()));
			inscLote.setText(convert(imovel.getInscricaoCadastralLote()));
			inscUnid.setText(convert(imovel.getInscricaoCadastralUnid()));

		} else {
			imovel = new Imovel();
		}
		
		setKeyChange();

	}

	private boolean imovelSincronizado() {
		if (imovel != null && imovel.getEnviado()) {
			return true;
		}
		return false;
	}

	public String convert(Integer i) {
		return i == null ? "" : i + "";
	}

	public void save() {

		imovelDao = new ImovelDao(getApplicationContext());

		imovel.setComando((Comando) comandoSpinner.getSelectedItem());
		imovel.setFatorLocalizacao((String) fatorLocal.getSelectedItem());
		imovel.setCreateAt(new Date());

		imovel.setInscricaoCadastralD(parseInt(inscd.getText().toString()));
		imovel.setInscricaoCadastralS(parseInt(inscs.getText().toString()));
		imovel.setInscricaoCadastralQuadra(parseInt(inscQuadra.getText()
				.toString()));
		imovel.setInscricaoCadastralLote(parseInt(inscLote.getText().toString()));
		imovel.setInscricaoCadastralUnid(parseInt(inscUnid.getText().toString()));

		if (imovel.getId() == null) {
			imovel.setGroupCreate(this.getSharedPreferences(
					SharedPreference.PREFS_NAME, 0).getString(
					SharedPreference.GROUPS, ""));
			imovelDao.create(imovel);
		} else {
			imovel.setGroupUpdate(this.getSharedPreferences(
					SharedPreference.PREFS_NAME, 0).getString(
					SharedPreference.GROUPS, ""));
			imovelDao.update(imovel);
		}

	}

	public Integer parseInt(String str) {
		try {
			return (Integer.parseInt(str));
		} catch (Exception e) {
			return null;
		}

	}

	public void next(View view) {
		if(inscs.getText().toString() == null || inscs.getText().toString().isEmpty() ){
			Toast.makeText(getApplicationContext(), "Campo Setor deve ser preenchido.", Toast.LENGTH_SHORT).show();
			inscs.setError("Campo obrigatório");
			return;
		}
		if(inscQuadra.getText().toString() == null || inscQuadra.getText().toString().isEmpty() ){
			Toast.makeText(getApplicationContext(), "Campo quadra deve ser preenchido.", Toast.LENGTH_SHORT).show();
			inscQuadra.setError("Campo obrigatório");
			return;
		}
		
		save();
		Intent intent = new Intent(getApplicationContext(),
				LocalizacaoActivity.class);

		System.err.println(imovel.getId());
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		finish();

		// finish();
	}

	public void previous(View view) {
		//NOTHING
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.create_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case R.id.finalizar:
			dialogSituacao();
			break;
		case R.id.sair:
			intent = new Intent(this, MenuActivity.class);
			startActivity(intent);
			try {
				finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void exibeMensagem(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}

	public void dialogSituacao() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Situação do Imóvel");

		final String[] items = new String[SituacaoImovel.values().length];
		int cont = 0;
		final Map<Integer, SituacaoImovel> map = new HashMap<Integer, SituacaoImovel>();

		for (SituacaoImovel si : SituacaoImovel.values()) {
			items[cont] = si.toString();
			map.put(cont, si);
			cont++;
		}

		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				imovel.setSituacaoImovel(map.get(which));
				save();
				imovel.getSituacaoImovel();
				finalCadastro();
			}
		});

		AlertDialog dsituacao = builder.create();
		dsituacao.show();
	}

	public void finalCadastro() {

		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setNeutralButton("Finalizar e usar como modelo",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								CreateMainActivity.class);

						imovel.setId(null);

						if (imovel.getEnderecoImovel() != null)
							imovel.getEnderecoImovel().setId(null);
						if (imovel.getEnderecoCorrespondencia() != null)
							imovel.getEnderecoCorrespondencia().setId(null);
						if (imovel.getAnnex() != null) {
							imovel.setAnnex(null);
						}
						if (imovel.getDimensoes() != null) {
							imovel.getDimensoes().setId(null);
						}
						if (imovel.getProprietarios() != null) {
							for (Proprietario p : imovel.getProprietarios()) {
								p.setId(null);
							}
						}

						intent.putExtra(IMOVEL, imovel);

						startActivity(intent);
						finish();

					}
				});

		builder.setPositiveButton("Finalizar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								MenuActivity.class);
						startActivity(intent);
						finish();

					}
				});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		builder.setMessage("Desejar finalizar o cadastro").setTitle(
				"Cadastro Finalizado");

		dialog = builder.create();
		dialog.show();
	}

	private void avisoCadastroSincronizado() {
		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setPositiveButton("Entendido",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});

		builder.setMessage("ATENÇÃO ! O presente imóvel já foi sincronizado com a base, qualquer mudança nesse dispositivo será desconsiderada pelo sistema." +
				" Para editar as informações contacte o administrado. ").setTitle(
				"Cadastro Sincronizado");

		dialog = builder.create();
		dialog.show();

	}
}
